<template>
    <el-cascader
        ref="elCascaderRef"
        v-bind="$attrs"
        :props="props"
        expand-trigger="hover"
        :options="cascaderOptions"
        :value="computedValue"
        @change="selectHandler"
        style="width: 100%;"
    ></el-cascader>
</template>
<script>
    export default {
        registryName: 'select-cascader',

        data (){
            return {
                cascaderOptions: [],
                optionsListMap: {},
                optionsItemMap: {}
            }
        },

        props: {
            value: String,

            url: String,

            props: {
                type: Object,
                default (){
                    return {
                        label: 'name',
                        value: 'id',
                        disabled:"disable"
                    }
                }
            }
        },

        computed: {
            computedValue (){
                if(this.value){
                    if(Object.keys(this.optionsListMap).length > 0){
                        return this.optionsListMap[this.value];
                    }else{
                        return [];
                    }
                }else{
                    return [];
                }
            }
        },

        methods: {
            loadOptions (url){
                const data = {};

                this.$ajax.json({ url, data }).then(({ data }) => {
                    this.optionsListMap = {};

                    this.optionsItemMap = {};

                    this.$set(this, 'cascaderOptions', emptyChildrenHandler.call(this, data));
                });

                function emptyChildrenHandler(source) {
                    source.forEach(item => {
                        item.disabled=item.state === '0';
                        this.optionsItemMap[item.id] = item;
                        item.parentPath && (
                            this.optionsListMap[item.id] = item.parentPath.substring(2).split(',').filter(item => item)
                        );

                        if(item.children && item.children.length > 0){
                            item.children = emptyChildrenHandler.call(this, item.children);
                        }else{
                            item.children = undefined;
                        }
                    });

                    return source;
                }
            },

            selectHandler (val){
                this.$emit('input', val[val.length - 1]);

                this.$nextTick(function () {
                    let instance = this.$getRef('elCascaderRef');
                    this.$emit('selectLabelChange',  instance.currentLabels);
                });
            }
        },

        watch: {
            url: {
                immediate: true,
                handler (v, o){
                    v && this.loadOptions(v);
                }
            }
        }
    }
</script>
